<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>运行日志列表</h3>
          <div class="header-actions">
            <el-button type="success" @click="exportLogs" :disabled="filteredLogs.length === 0">
              <el-icon><el-icon-download /></el-icon> 导出日志
            </el-button>
            <el-button v-if="currentEvent" type="danger" @click="confirmClearEventLogs">
              <el-icon><el-icon-delete /></el-icon> 清空当前事件日志
            </el-button>
          </div>
        </div>
      </template>
      
      <el-form :inline="true" class="search-form">
        <el-form-item label="事件">
          <el-select v-model="searchForm.eventId" placeholder="选择事件" clearable @change="handleEventChange">
            <el-option
              v-for="item in events"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="运行状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
            <el-option label="错误" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><el-icon-search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><el-icon-refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table 
        :data="filteredLogs" 
        style="width: 100%" 
        v-loading="loading"
        :default-sort="{ prop: 'runTime', order: 'descending' }"
        row-key="id"
        stripe
        highlight-current-row
      >
        <el-table-column prop="id" label="日志ID" width="180" />
        <el-table-column prop="eventName" label="事件名称" />
        <el-table-column prop="runTime" label="运行时间" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.runTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="运行时长" sortable>
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="运行状态" sortable>
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="result" label="运行结果" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewLogDetail(row.id)">
              <el-icon><el-icon-view /></el-icon> 详情
            </el-button>
            <el-button type="danger" size="small" @click="confirmDeleteLog(row.id)">
              <el-icon><el-icon-delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalLogs"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情弹窗 -->
    <el-dialog
      v-model="logDetailDialogVisible"
      title="日志详情"
      width="800px"
      top="5vh"
    >
      <div v-if="currentLogDetail" class="log-detail-container">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLogDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="事件名称">{{ currentLogDetail.eventName }}</el-descriptions-item>
          <el-descriptions-item label="运行时间">{{ formatDateTime(currentLogDetail.runTime) }}</el-descriptions-item>
          <el-descriptions-item label="运行时长">{{ formatDuration(currentLogDetail.duration) }}</el-descriptions-item>
          <el-descriptions-item label="运行状态">
            <el-tag :type="getStatusType(currentLogDetail.status)">{{ getStatusText(currentLogDetail.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="运行结果">{{ currentLogDetail.result }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-header">
          <h4 class="detail-subtitle">日志内容</h4>
          <el-button size="small" type="primary" @click="copyLogContent">复制日志</el-button>
        </div>
        
        <div class="log-container">
          <div v-if="currentLogDetail.logs && currentLogDetail.logs.length > 0">
            <div 
              v-for="(log, index) in currentLogDetail.logs" 
              :key="index"
              :class="['log-item', log.type]"
            >
              <span class="log-timestamp">{{ formatDateTime(log.timestamp) }}</span>
              <span :class="['log-badge', log.type]">{{ getLogTypeText(log.type) }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
          <div v-else class="empty-log">
            <el-empty description="无日志内容" />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="logDetailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete as ElIconDelete, View as ElIconView, Search as ElIconSearch, 
         Download as ElIconDownload, Refresh as ElIconRefresh } from '@element-plus/icons-vue'

const store = useStore()
const route = useRoute()
const router = useRouter()

const loading = ref(false)
const logDetailDialogVisible = ref(false)
const currentLogDetail = ref(null)
const currentEvent = ref(null)

const searchForm = ref({
  eventId: '',
  status: '',
  timeRange: null
})

// 获取路由参数中的事件ID
const eventIdFromRoute = computed(() => route.params.eventId)

// 监听路由参数变化
watch(eventIdFromRoute, (newEventId) => {
  if (newEventId) {
    searchForm.value.eventId = newEventId
    loadEventLogs()
  }
}, { immediate: true })

// 从Vuex获取分页信息
const currentPage = computed({
  get: () => store.state.currentPage,
  set: (val) => store.commit('SET_CURRENT_PAGE', val)
})

const pageSize = computed({
  get: () => store.state.pageSize,
  set: (val) => store.commit('SET_PAGE_SIZE', val)
})

const totalLogs = computed(() => store.state.totalLogs)

// 根据当前是否有指定事件，获取不同的日志列表
const logs = computed(() => {
  return searchForm.value.eventId ? store.state.currentEventLogs : store.state.eventLogs
})

// 过滤日志列表
const filteredLogs = computed(() => {
  return logs.value.filter(log => {
    // 状态过滤
    const statusMatch = searchForm.value.status ? log.status === searchForm.value.status : true
    
    // 时间范围过滤
    let timeMatch = true
    if (searchForm.value.timeRange && searchForm.value.timeRange.length === 2) {
      const logTime = new Date(log.runTime).getTime()
      const startTime = new Date(searchForm.value.timeRange[0]).getTime()
      const endTime = new Date(searchForm.value.timeRange[1]).getTime()
      timeMatch = logTime >= startTime && logTime <= endTime
    }
    
    return statusMatch && timeMatch
  })
})

// 获取所有事件列表
const events = computed(() => store.state.events)

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 格式化运行时长
const formatDuration = (ms) => {
  if (!ms) return '0秒'
  if (ms < 1000) return `${ms}毫秒`
  
  const seconds = Math.floor(ms / 1000)
  if (seconds < 60) return `${seconds}秒`
  
  const minutes = Math.floor(seconds / 60)
  const remainSeconds = seconds % 60
  return `${minutes}分${remainSeconds}秒`
}

// 获取状态显示类型
const getStatusType = (status) => {
  switch (status) {
    case 'success': return 'success'
    case 'failed': return 'warning'
    case 'error': return 'danger'
    default: return 'info'
  }
}

// 获取状态显示文本
const getStatusText = (status) => {
  switch (status) {
    case 'success': return '成功'
    case 'failed': return '失败'
    case 'error': return '错误'
    default: return status
  }
}

// 获取日志类型显示文本
const getLogTypeText = (type) => {
  switch (type) {
    case 'info': return '信息'
    case 'success': return '成功'
    case 'error': return '错误'
    case 'warning': return '警告'
    default: return type
  }
}

// 复制日志内容
const copyLogContent = () => {
  if (!currentLogDetail.value || !currentLogDetail.value.logs) return
  
  const logText = currentLogDetail.value.logs.map(log => 
    `${formatDateTime(log.timestamp)} [${getLogTypeText(log.type)}] ${log.message}`
  ).join('\n')
  
  navigator.clipboard.writeText(logText)
    .then(() => ElMessage.success('日志内容已复制到剪贴板'))
    .catch(() => ElMessage.error('复制失败，请手动复制'))
}

// 导出日志
const exportLogs = () => {
  if (filteredLogs.value.length === 0) return
  
  const data = filteredLogs.value.map(log => ({
    '日志ID': log.id,
    '事件名称': log.eventName,
    '运行时间': formatDateTime(log.runTime),
    '运行时长': formatDuration(log.duration),
    '运行状态': getStatusText(log.status),
    '运行结果': log.result
  }))
  
  const csvContent = [
    Object.keys(data[0]).join(','),
    ...data.map(row => Object.values(row).map(value => 
      `"${String(value).replace(/"/g, '""')}"`
    ).join(','))
  ].join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  
  const link = document.createElement('a')
  link.setAttribute('href', url)
  link.setAttribute('download', `日志记录_${new Date().toISOString().split('T')[0]}.csv`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  
  ElMessage.success('日志导出成功')
}

// 加载日志列表
const loadLogs = async () => {
  loading.value = true
  try {
    await store.dispatch('fetchAllEventLogs', {
      page: currentPage.value,
      limit: pageSize.value
    })
  } finally {
    loading.value = false
  }
}

// 加载特定事件的日志
const loadEventLogs = async () => {
  if (!searchForm.value.eventId) {
    return loadLogs()
  }
  
  loading.value = true
  try {
    // 加载事件信息
    currentEvent.value = await store.dispatch('fetchEventById', searchForm.value.eventId)
    
    // 加载该事件的日志
    await store.dispatch('fetchEventLogs', {
      eventId: searchForm.value.eventId,
      page: currentPage.value,
      limit: pageSize.value
    })
  } finally {
    loading.value = false
  }
}

// 查看日志详情
const viewLogDetail = async (logId) => {
  try {
    currentLogDetail.value = await store.dispatch('getLogDetail', logId)
    logDetailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取日志详情失败')
  }
}

// 确认删除日志
const confirmDeleteLog = (logId) => {
  ElMessageBox.confirm('确认删除该日志记录？此操作不可恢复！', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const success = await store.dispatch('deleteLog', logId)
      if (success) {
        ElMessage.success('删除成功')
        // 如果有选中事件，重新加载该事件的日志
        if (searchForm.value.eventId) {
          loadEventLogs()
        } else {
          loadLogs()
        }
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 确认清空事件日志
const confirmClearEventLogs = () => {
  if (!searchForm.value.eventId) return
  
  ElMessageBox.confirm(`确认清空事件"${currentEvent.value?.name}"的所有日志记录？此操作不可恢复！`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const success = await store.dispatch('clearEventLogs', searchForm.value.eventId)
      if (success) {
        ElMessage.success('清空成功')
        loadEventLogs()
      } else {
        ElMessage.error('清空失败')
      }
    } catch (error) {
      ElMessage.error('清空失败')
    }
  }).catch(() => {})
}

// 事件选择变更处理
const handleEventChange = (eventId) => {
  if (eventId) {
    // 如果选择了事件，更新路由
    router.push(`/logs/event/${eventId}`)
  } else {
    // 如果清空了事件选择，返回日志主页
    router.push('/logs')
    currentEvent.value = null
    loadLogs()
  }
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.status = ''
  searchForm.value.timeRange = null
  
  if (searchForm.value.eventId) {
    // 如果有选择事件，只重置状态搜索和时间范围
    loadEventLogs()
  } else {
    // 全部重置
    router.push('/logs')
    currentEvent.value = null
    loadLogs()
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  if (searchForm.value.eventId) {
    loadEventLogs()
  } else {
    loadLogs()
  }
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  if (searchForm.value.eventId) {
    loadEventLogs()
  } else {
    loadLogs()
  }
}

onMounted(async () => {
  // 加载事件列表
  await store.dispatch('fetchEvents')
  
  // 根据路由参数加载日志
  if (eventIdFromRoute.value) {
    searchForm.value.eventId = eventIdFromRoute.value
    loadEventLogs()
  } else {
    loadLogs()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.log-detail-container {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0 10px;
}

.detail-subtitle {
  margin: 0;
  font-size: 16px;
  color: #606266;
}

.log-container {
  height: 400px;
  overflow-y: auto;
  background-color: #303133;
  color: #fff;
  font-family: monospace;
  padding: 10px;
  border-radius: 4px;
}

.log-item {
  padding: 4px 0;
  line-height: 1.4;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.log-item.info {
  color: #e6e6e6;
}

.log-item.success {
  color: #67c23a;
}

.log-item.warning {
  color: #e6a23c;
}

.log-item.error {
  color: #f56c6c;
}

.log-timestamp {
  color: #909399;
}

.log-badge {
  padding: 1px 4px;
  border-radius: 3px;
  font-size: 12px;
}

.log-badge.info {
  background-color: #909399;
  color: white;
}

.log-badge.success {
  background-color: #67c23a;
  color: white;
}

.log-badge.warning {
  background-color: #e6a23c;
  color: white;
}

.log-badge.error {
  background-color: #f56c6c;
  color: white;
}

.log-message {
  flex: 1;
  word-break: break-all;
}

.empty-log {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}
</style> 